package cn.com.pxto.commons;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;


//Cookie������

public class CookieUtils {
	static Logger logger = Logger.getLogger(CookieUtils.class);

	public static void writeCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {// дCookie
		Cookie cookie = new Cookie(cookieName, cookieValue);
		cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
		
	}
    
	public static String getCookie(HttpServletRequest request, String cookieName) {// ��Cookie
		String result = null;
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(cookieName)) {
					result = cookies[i].getValue();
				}
			}
		}
		return result;
	}

	public static void removeCookie(HttpServletRequest request,HttpServletResponse response, String cookieName) {// ɾ��Cookie
		if (cookieName == null)
			return;
		Cookie cookies[] = request.getCookies();

		if (cookies != null&&cookies.length > 0) {
			Cookie sCookie = null;
			String sname = null;
			for (int i = 0; i < cookies.length; i++) {
				sCookie = cookies[i];
				sname = sCookie.getName();
				if (sname != null && sname.equals(cookieName)) {
					logger.debug("remove cookie : "+cookieName);
					sCookie.setMaxAge(0);// ʹcookie����
					if(sCookie.getName().equals("uin")){
					   logger.debug("set cookieuin to -1");
					   sCookie.setValue("-1");
					}  
					response.addCookie(sCookie);	
				}
			}

		}

	}
	public static void removeCookie(HttpServletRequest request, String cookieName) {// ɾ��Cookie
		if (cookieName == null)
			return;
		Cookie cookies[] = request.getCookies();

		if (cookies != null && cookies.length > 0) {
			Cookie sCookie = null;
			String sname = null;
			for (int i = 0; i < cookies.length; i++) {
				sCookie = cookies[i];
				sname = sCookie.getName();
				if (sname != null && sname.equals(cookieName)) {
				
					logger.debug("remove cookie : "+cookieName);
					sCookie.setMaxAge(-1);// ʹcookie����
					if(sCookie.getName().equals("uin")){
					   logger.debug("set cookieuin to -1");
					   sCookie.setValue("-1");
					}  
				}
			}

		}

	}  
}

